use axum::{
    extract::{Json, State},
    http::StatusCode,
    response::{IntoResponse, Response},
};
use sqlx::MySqlPool;
use crate::models::{Handover, HandoverCreateRequest};

pub async fn getall(
    State(pool): State<MySqlPool>
) -> Response {
    match sqlx::query_as::<_, Handover>(
        "SELECT * FROM handover_information ORDER BY date"
    )
    .fetch_all(&pool)
    .await {
        Ok(results) => {
            (StatusCode::OK, Json(results)).into_response()
        },
        Err(e) => {
            println!("数据库查询错误：{:?}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({
                    "error": "数据库查询失败！"
                }))
            ).into_response()
        }
    }
}

pub async fn create(
    State(pool): State<MySqlPool>,
    Json(create_req): Json<HandoverCreateRequest>,
) -> Response {
    // 加入新接班数据
    match sqlx::query(
        r#"
        INSERT INTO handover_information (date, succession, amount, notes)
        VALUES (?, ?, ?, ?)
        "#
    )
    .bind(&create_req.date)
    .bind(&create_req.succession)
    .bind(&create_req.amount)
    .bind(&create_req.notes)
    .execute(&pool)
    .await {
        Ok(_) => {
            (StatusCode::OK, Json(serde_json::json!({
                "message": "接班信息创建成功"
            }))).into_response()
        },
        Err(e) => {
            println!("数据库插入错误：{:?}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({
                    "error": "接班信息创建失败"
                }))
            ).into_response()
        }
    }
}

// pub async fn delete(
//     State(pool): State<MySqlPool>,
//     Json(commodity_delete_req): Json<HandoverDeleteRequest>,
// ) -> Response {
//     // 如果商品不存在，则创建新商品
//     match sqlx::query(
//     "DELETE FROM commodity_information WHERE id = ?"
//     )
//     .bind(&commodity_delete_req.id)
//     .execute(&pool)
//     .await {
//         Ok(_) => {
//             (StatusCode::OK, Json(serde_json::json!({
//                 "message": "商品删除成功"
//             }))).into_response()
//         },
//         Err(e) => {
//             println!("数据库删除错误：{:?}", e);
//             (
//                 StatusCode::INTERNAL_SERVER_ERROR,
//                 Json(serde_json::json!({
//                     "error": "商品删除失败"
//                 }))
//             ).into_response()
//         }
//     }
// }